package cn.sunxiansheng.consumer.error;

import com.rabbitmq.client.LongString;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;

import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * Description: 错误消息处理器
 *
 * @Author sun
 * @Create 2024/12/31 20:32
 * @Version 1.0
 */
@Slf4j
public class ErrorMessageHandler {

    public static void handleErrorMessage(String listenerName, Message message) {
        // 获取消息属性
        MessageProperties messageProperties = message.getMessageProperties();
        String messageBody = new String(message.getBody(), StandardCharsets.UTF_8);
        Map<String, Object> headers = messageProperties.getHeaders();

        // 从消息头部获取异常信息
        String exceptionMessage = (String) headers.get("x-exception-message");
        String originalExchange = (String) headers.get("x-original-exchange");
        String originalRoutingKey = (String) headers.get("x-original-routingKey");

        // 处理LongString类型的异常堆栈跟踪信息
        String exceptionStackTrace = null;
        if (headers.containsKey("x-exception-stacktrace")) {
            Object stacktraceObject = headers.get("x-exception-stacktrace");
            if (stacktraceObject instanceof LongString) {
                exceptionStackTrace = stacktraceObject.toString();
            }
        }

        // 格式化输出所有信息，并在前后添加分割线
        log.error("\n-------------------------------\n" +
                        "MQ错误监听队列: {}\n" +
                        "原始交换机: {}\n" +
                        "原始路由键: {}\n" +
                        "原始信息: {}\n" +
                        "异常信息: {}\n" +
                        "异常堆栈: {}\n" +
                        "-------------------------------",
                listenerName, originalExchange, originalRoutingKey, messageBody, exceptionMessage, exceptionStackTrace);
    }
}